import config from '@/config'
import cookie from '@/utils/store/cookie.js'

const responseStatusCallback = response => {
  uni.showToast({
  	title: response.data.msg,
	icon: 'none',
  	duration: 2000
  })
  return Promise.reject(response)
}

const service = ( url, payload = {}, method = 'GET' ) => {
	
	const token = cookie.get('login_status')
	let header = {}
	if (token) header['Authorization'] = 'Bearer ' + token
	// if (openid) payload.openid = openid
	// console.info(url, payload, method, `${config.api}/api${url}`)
	
	return new Promise((resolve, reject) => {
		uni.request({
		    url: `${config.api}${url}`,
			method,
		    data: payload,
		    header,
		    success: res => {
				// console.info('请求数据:' + JSON.stringify(res))
				console.info(res)
				if (res.statusCode == 200) {
					if (res.data.code !== 200) {
						if (res.data.code === 401) {
							uni.navigateTo({
								url: '/pages/index/index'
							})
							return
						}
						return responseStatusCallback(res)
					}
					return resolve(res.data)
				}
				return responseStatusCallback(res)
		    },
			fail: res => {
				return responseStatusCallback(res)
			}
		})
	})
	
}

export default service